﻿using System;
using Android.App;
using Android.OS;
using Android.Runtime;
using Android.Views;
using AndroidX.AppCompat.Widget;
using AndroidX.AppCompat.App;
using Google.Android.Material.FloatingActionButton;
using Google.Android.Material.Snackbar;
using Android.Content;
using AndroidX.Core.Content;
using Android;
using Android.Content.PM;
using System.Net;
using System.Net.Sockets;
using Xamarin.Essentials;
using MiPadAndroid.Services;

namespace MiPadAndroid
{
    [Activity(Label = "@string/app_name", Theme = "@style/AppTheme.NoActionBar", MainLauncher = true)]
    public class MainActivity : AppCompatActivity
    {
        Android.Widget.EditText editText;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            SetContentView(Resource.Layout.activity_main);

            Toolbar toolbar = FindViewById<Toolbar>(Resource.Id.toolbar);
            SetSupportActionBar(toolbar);

            FloatingActionButton fab = FindViewById<FloatingActionButton>(Resource.Id.fab);
            fab.Click += FabOnClick;

            if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
            {
                Android.Net.Uri uri = Android.Net.Uri.Parse("package:" + Android.App.Application.Context.PackageName);
                // 浮到最上层
                if (!Android.Provider.Settings.CanDrawOverlays(this))
                {
                    StartActivityForResult(new Intent(Android.Provider.Settings.ActionManageOverlayPermission, uri), 0);
                }
                // 查看系统信息
                if (!Android.Provider.Settings.System.CanWrite(this))
                {
                    StartActivityForResult(new Intent(Android.Provider.Settings.ActionManageWriteSettings, uri), 0);
                }
            }
            editText = this.FindViewById<Android.Widget.EditText>(Resource.Id.txtIP);
            MainThread.BeginInvokeOnMainThread(async () =>
            {
                string ip = await Xamarin.Essentials.SecureStorage.GetAsync("ip");
                if (!string.IsNullOrWhiteSpace(ip))
                {
                    editText.Text = ip;
                    FabOnClick(fab, null);
                }
                else
                {
                    editText.Text = MqttService.GetIP();
                }
            });
        }

        public override bool OnCreateOptionsMenu(IMenu menu)
        {
            MenuInflater.Inflate(Resource.Menu.menu_main, menu);
            return true;
        }

        public override bool OnOptionsItemSelected(IMenuItem item)
        {
            int id = item.ItemId;
            if (id == Resource.Id.action_settings)
            {
                return true;
            }

            return base.OnOptionsItemSelected(item);
        }

        private void FabOnClick(object sender, EventArgs eventArgs)
        {
            string ip = editText.Text.Trim();
            // 检测IP是否连通
            if (MqttService.TcpClientCheck(ip))
            {
                // 保存配置
                SecureStorage.SetAsync("ip", ip);

                Intent intent = new Intent(Application.Context, typeof(HomeActivity));
                intent.PutExtra("ip", ip);
                StartActivity(intent);
            }
            else
            {
                View view = (View)sender;
                Snackbar.Make(view, "当前IP的MQTT服务无法访问", Snackbar.LengthLong)
                    .SetAction("Action", (View.IOnClickListener)null).Show();
            }
        }

        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
	}
}
